<script setup>
  // 无缝滚动需要自行复制2份item数据
  const props = defineProps({
    speed: {
      default: 1
    },
    gap: {
      default: '4'
    }
  })

  const childs = ref([])
  const marqueeRef = ref(null)
  const scrollEnd = ref(0)
  let requestAnimationFrameId = null

  const ulStyles = computed(() => {
    switch (props.gap) {
      case '2': return 'gap-2'
      case '4': return 'gap-4'
      case '6': return 'gap-6'
      case '8': return 'gap-8'
      case '10': return 'gap-10'
      case '12': return 'gap-12'
      case '14': return 'gap-14'
      case '16': return 'gap-16'
      case '18': return 'gap-18'
      case '20': return 'gap-20'
    }
  })
  // const totalWidth = computed(() => {
  //   return childs.value.reduce((total, child) => {
  //     return total + child.width
  //   }, 0)
  // })

  function addChildRect(child) {
    childs.value.push(child)
  }

  function loop() {
    marqueeRef.value.scrollLeft += Number(props.speed)
    requestAnimationFrameId = requestAnimationFrame(loop)
    if (marqueeRef.value.scrollLeft >= scrollEnd.value) {
      marqueeRef.value.scrollLeft = 0
    }
  }

  function calcScrollEnd() {
    // const rect = marqueeRef.value.getBoundingClientRect()
    scrollEnd.value = marqueeRef.value.scrollWidth / 2
  }


  function onEnter() {
    cancelAnimationFrame(requestAnimationFrameId)
  }

  function onLeave() {
    loop()
  }

  provide('$parent', { addChildRect })

  onMounted(() => {
    calcScrollEnd()
    loop()
  })
</script>

<template>
  <div class=" marquee">
    <div class="overflow-hidden" ref="marqueeRef" @mouseenter="onEnter" @mouseleave="onLeave">
      <ul class="flex items-start" :class="ulStyles">
        <slot />
      </ul>
    </div>
  </div>
</template>

<style lang="scss" scoped>
  .marquee {
    @apply relative;

    &::before,
    &::after {
      content: '';
      @apply absolute top-0 h-full w-20;
    }

    &::before {
      @apply left-0;
      background-image: linear-gradient(90deg, rgba(255, 255, 255, 1), rgba(255, 255, 255, 0));
    }

    &::after {
      @apply right-0;
      background-image: linear-gradient(270deg, rgba(255, 255, 255, 1), rgba(255, 255, 255, 0));
    }
  }
</style>